<template>
  <el-dialog
    title="编辑会员信息"
    :visible.sync="dialogVisible"
    width="1000px"
    :close-on-click-modal="false"
    :before-close="handleClose"
    class="member-edit-dialog"
  >
    <el-form
      :model="memberForm"
      :rules="rules"
      ref="memberFormRef"
      label-width="90px"
      v-loading="loading"
    >

      <h4 class="section-title">账号信息</h4>

      <el-form-item label="会员头像" prop="avatarUrl" class="avatar-uploader-item">
        <div class="avatar-uploader-container">
          <img :src="memberForm.avatarUrl" class="member-avatar">
          <div class="avatar-mask">
            <el-button type="text" size="mini" @click="uploadAvatar">更改</el-button>
          </div>
          <input type="file" ref="fileInput" style="display: none;" @change="handleFileChange">
        </div>
      </el-form-item>

      <el-form-item label="会员昵称" prop="nickname">
        <el-input v-model="memberForm.nickname" placeholder="请填写" clearable />
      </el-form-item>

      <el-form-item label="会员账号" prop="account">
        <el-input v-model="memberForm.account" placeholder="请填写" clearable>
          <template slot="suffix">
            <span class="input-tip">请填写手机号</span>
          </template>
        </el-input>
      </el-form-item>

      <el-form-item label="会员状态" prop="status">
        <el-radio-group v-model="memberForm.status">
          <el-radio :label="1">正常</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>

      <h4 class="section-title">会员信息</h4>

      <el-form-item label="会员性别" prop="gender">
        <el-radio-group v-model="memberForm.gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="0">女</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="会员生日" prop="birthday">
        <el-date-picker
          v-model="memberForm.birthday"
          type="date"
          placeholder="请选择"
          style="width: 100%;"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm('memberFormRef')" :loading="saveLoading">保存</el-button>
      <el-button @click="handleClose">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
export default {
  props: {
    // 控制弹窗是否显示
    visible: {
      type: Boolean,
      default: false
    },
    // 传入的会员ID，用于加载和保存数据
    memberId: {
      type: [String, Number],
      default: null
    }
  },
  data() {
    // 手机号校验规则
    var validateAccount = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入会员账号（手机号）'))
      } else if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('手机号格式不正确'))
      } else {
        callback()
      }
    }

    return {
      dialogVisible: this.visible,
      loading: false,     // 加载数据时的 loading
      saveLoading: false, // 保存按钮的 loading

      // 表单数据模型
      memberForm: {
        avatarUrl: '/static/default-avatar.png', // 默认头像
        nickname: '',
        account: '',
        status: 1, // 1: 正常, 0: 禁用
        gender: 1, // 1: 男, 0: 女
        birthday: ''
      },

      // 表单校验规则
      rules: {
        avatarUrl: [
          { required: true, message: '请上传会员头像', trigger: 'change' }
        ],
        nickname: [
          { required: true, message: '请输入会员昵称', trigger: 'blur' },
          { max: 20, message: '长度不能超过 20 个字符', trigger: 'blur' }
        ],
        account: [
          { required: true, validator: validateAccount, trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择会员状态', trigger: 'change' }
        ],
        birthday: [
          { required: true, message: '请选择会员生日', trigger: 'change' }
        ]
      }
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        // 弹窗打开时，重置表单并加载数据
        this.resetForm('memberFormRef')
        if (this.memberId) {
          this.loadMemberData(this.memberId)
        } else {
          // 新增模式下的默认值处理
          this.memberForm.avatarUrl = '/static/default-avatar.png'
        }
      }
    }
  },
  methods: {
    /**
     * @description 关闭弹窗并通知父组件
     */
    handleClose() {
      // 触发父组件的 update:visible 事件来关闭弹窗
      this.$emit('update:visible', false)
    },

    /**
     * @description 加载会员详情数据用于编辑
     */
    loadMemberData(id) {
      this.loading = true
      console.log(`正在加载会员 ${id} 的编辑数据...`)

      // 模拟 API 请求
      setTimeout(() => {
        this.loading = false
        // 假设 API 返回的数据
        const mockData = {
          avatarUrl: '/static/member-avatar.png',
          nickname: '黄飞马',
          account: '13636373637',
          status: 1,
          gender: 1,
          birthday: '1995-10-15'
        }
        this.memberForm = mockData
        this.$message.success('数据加载成功')
      }, 500)
    },

    /**
     * @description 点击“更改”按钮，触发文件选择
     */
    uploadAvatar() {
      this.$refs.fileInput.click()
    },

    /**
     * @description 文件选择变化时的处理
     */
    handleFileChange(event) {
      const file = event.target.files[0]
      if (file) {
        // 实际应用中：调用上传 API，成功后更新 memberForm.avatarUrl
        const reader = new FileReader()
        reader.onload = (e) => {
          this.memberForm.avatarUrl = e.target.result // 仅用于本地预览
          // TODO: 调用上传API，并将真实返回的URL赋值给 memberForm.avatarUrl
          this.$message.info('头像已选择，待上传...')
        }
        reader.readAsDataURL(file)
      }
    },

    /**
     * @description 提交表单（保存）
     */
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveLoading = true
          console.log('提交的表单数据:', this.memberForm)

          // 模拟 API 保存请求
          const apiCall = this.memberId ? this.$api.updateMember : this.$api.addMember

          setTimeout(() => {
            this.saveLoading = false
            this.$message.success('会员信息保存成功！')
            this.$emit('success') // 通知父组件操作成功，可以刷新列表
            this.handleClose() // 关闭弹窗
          }, 1000)
        } else {
          this.$message.error('表单校验失败，请检查填写内容！')
          return false
        }
      })
    },

    /**
     * @description 重置表单到初始状态
     */
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields()
      }
      // 手动重置非表单项
      this.memberForm = this.$options.data.call(this).memberForm
    }
  }
}
</script>

<style lang="scss" scoped>
.member-edit-dialog {

  .section-title {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
    margin: 20px 0 15px 0;
    padding-left: 10px;
    border-left: 4px solid #409EFF; /* Element UI 主题色 */
  }

  /* 会员头像上传样式 */
  .avatar-uploader-item {
    margin-bottom: 25px;
  }
  .avatar-uploader-container {
    position: relative;
    width: 80px;
    height: 80px;
    border-radius: 50%;
    overflow: hidden;
    cursor: pointer;

    .member-avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .avatar-mask {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.5);
      display: flex;
      justify-content: center;
      align-items: center;
      opacity: 0;
      transition: opacity 0.3s;

      .el-button {
        color: #fff;
      }
    }

    &:hover .avatar-mask {
      opacity: 1;
    }
  }

  /* 输入框提示信息样式（对应设计稿中的红色提示） */
  .input-tip {
    color: #F56C6C; /* Element UI 错误色 */
    font-size: 12px;
    margin-left: 10px;
    white-space: nowrap;
  }

  /* 调整 label 宽度 */
  ::v-deep .el-form-item__label {
      text-align: left;
  }
}
</style>
